package util.database.init;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class DbUtil 
{
	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure("recreateDb.xml")
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public static void reCreateDb(String dbName)
	{
		Session session = getSessionFactory().openSession();
		Transaction transaction = null;
		transaction = session.beginTransaction();
		try 
		{
				SQLQuery q = session.createSQLQuery("drop database " + dbName);
				int a = q.executeUpdate();
				System.out.println(a + "row effected");
				SQLQuery q2 = session.createSQLQuery("create database " + dbName);
				int a2 = q2.executeUpdate();
				System.out.println(a2 + "row effected");
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
		    System.out.println("Database does not exists");
		    try
		    {
		    	SQLQuery q2 = session.createSQLQuery("create database advprop");
		    	int a2 = q2.executeUpdate();
		    	System.out.println(a2 + "row effected");
		    }
		    catch(HibernateException he2)
		    {
		    	transaction.rollback();
		    	he2.printStackTrace();
		    	System.out.println("Can't recreate database");
		    }
		}
		finally 
		{
			session.close();
		}
	}
}
